import React from 'react';
import { inject, observer } from 'mobx-react';
import { observable, action, toJS } from 'mobx';
import {
  WeaTop, WeaRightMenu, WeaTools, WeaErrorPage
  , WeaRadioGroup, WeaTableEdit
} from 'ecCom';
import { WeaTableNew } from 'comsMobx';
import { Button } from 'antd';
import { isEmpty } from 'lodash';
import moment from 'moment';
const WeaTable = WeaTableNew.WeaTable;
import { WeaLocaleProvider } from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;

import RoomPlanDialog from '../public/roomPlan/index';
import MeetingDialog from '../public/dialog/index';



@inject('meetingMeetingReport')
@observer
class MeetingReport extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      height: 396,
      RoomPlanContainer: false,
      dialogType: 'preview',
      meetingId: '',
      visible: false,
    }
  }
  componentDidMount() {
    const { getReportCondition } = this.props.meetingMeetingReport;
    getReportCondition();
    //表格滚动高度
    setInterval  (() => {
      const h = $('#meeting-report-con').height();
      let listHeight=0;
      $('#meeting-report-table') && $('#meeting-report-table').height()>0 ? (listHeight=$('#meeting-report-table').height()): listHeight=0;
      let realHeight=h-listHeight-190;
      let currentHeight=this.state.height;
      if(currentHeight!==realHeight){
        this.setState({ height: realHeight});
      }
    }, 500);
  }


  exportExcel = () => {
    const { exportToExcel} = this.props.meetingMeetingReport;
    exportToExcel()
    //exportExcelUrl  =encodeURI('/api/meeting/report/exportExcel?tableKey='+JSON.stringify(reportData));
  }

  getButtons = () => {
    return [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@xkehba@doExportExcel`} type='primary' onClick={this.exportExcel}>{`${getLabel(383379, "导出到")}Excel`}</Button>];
  }

  getRightMenu = () => {
    return [{
      key: 'export',
      content: `${getLabel(383379, "导出到")}Excel`,
      icon: <i className='icon-coms-Preservation' />,
      onClick: this.exportExcel
    }];
  }

  render() {
    const { meetingMeetingReport } = this.props;
    let { reportCol, reportData, getDetail, tableStore, col, row
      , setState, condition, getReportData, year, conditionParams, exportExcelUrl=''} = meetingMeetingReport;
    let {RoomPlanContainer, visible, dialogType, meetingId} = this.state;
    conditionParams = toJS(conditionParams);
    reportCol = toJS(reportCol);
    reportData = toJS(reportData);
    condition = toJS(condition);
    let datas = [];
    reportData.forEach(v => {
      let temp = {};
      Object.keys(v).forEach(o => {
        let ol = 0;
        if(o == 'type'){
          ol = v[o];
        }else{
          ol = v[o] === '' ? 0 : v[o];
        }
        temp[o] = ol + '__' + o;
      })
      datas.push(temp);
    })
    let columns = [];
    
    Object.keys(reportCol).forEach(v => {
      columns.push({
        checkType: '',
        title: reportCol[v],
        dataIndex: v,
        key: v,
        width: v === 'type' ? '200px' : '7%',
        type: 'CUSTOM',
        render: (textValue, record, index, con) => {
          const text = textValue.slice(0, textValue.indexOf('__'));
          const month = Object.keys(reportCol).indexOf(textValue.slice(textValue.indexOf('__') + 2));
          return v === 'type' ? (
            <div className='report-type' title={text}>{text}</div>
          ) : (
              <div className={`report-content ${col === month && row === index && 'report-content-active'}`}
                onClick={(e) => {
                  let targetDom = $(e.target).parents("td"),
                    params = {
                      year,
                      month,
                      orgType: conditionParams.orgType,
                      yearType: conditionParams.yearType,
                      type: record.typeId.substring(0,record.typeId.indexOf('__'))
                    };
                  if (conditionParams.orgType === '2') params = { ...params, subid: conditionParams.subid};
                  if (conditionParams.orgType === '3') params = { ...params, depid: conditionParams.depid};
                  !isEmpty(text) ?
                    col === month && row === index ?
                      setState({ row: -1, col: 0 })
                      : setState({ row: index, col: month, type:record.typeId.substring(0,record.typeId.indexOf('__')) }) && getDetail(params)
                    : setState({ row: -1, col: 0 })
                }}>{text}</div>
            )
        }
      })
    })
    return (
      <div className="meeting-report">
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@1nqik1`}
          datas={this.getRightMenu()}
          collectParams={{
            favname: getLabel(383478, "年度会议统计表"),
            favouritetype: 5,
            objid: 0,
            importantlevel: 1,
          }}>
          <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@mngzuo`}
            title={getLabel(383478, "年度会议统计表")}
            icon={<i className='icon-coms-meeting' />}
            iconBgcolor='#f14a2d'
            buttons={this.getButtons()}
            buttonSpace={10}
            showDropIcon={true}
            dropMenuDatas={this.getRightMenu()}
            dropMenuProps={{
              collectParams: {
                favname: getLabel(383478, "年度会议统计表"),
                favouritetype: 5,
                objid: 0,
                importantlevel: 1,
              }
            }}>
            <div className='meeting-report-con' id='meeting-report-con'>
              <WeaRadioGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaRadioGroup@jd9kua`}
                config={condition}
                onChange={(params) => {
                  //更新year 
                  const yearNow = moment().year();
                  params.yearType && params.yearType === '1' && setState({ year: yearNow });
                  params.yearType && params.yearType === '2' && setState({ year: yearNow - 1 });
                  params.cusyear && params.cusyear !== '' && setState({ year: params.cusyear });
                  //获取会议信息
                  let bool = true;
                  params.yearType && params.yearType === '3' && params.cusyear && params.cusyear === '' && (bool = false);
                  params.orgType && params.orgType === '3' && params.cusyear === '' && (bool = false);
                  setState({ conditionParams: { ...conditionParams, ...params } });
                  bool && getReportData({...conditionParams,...params});
                }}
                beforeInit={
                  (config, lastValueMap, cb) => {
                    cb(lastValueMap);
                  }
                }
              />
              <div className='meeting-report-table-main' style={{ height: '80%' }}>
                <WeaTableEdit ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEdit@l2wogq`}
                  columns={columns}
                  datas={datas}
                  showDelete={false}
                  showCopy={false}
                  showAdd={false}
                  getRowSelection={() => null}
                  tableProps={{
                    scroll: { x: false, y: this.state.height }
                  }}
                  onChange={statusData => setState({ statusData })} />
              </div>
              {
                col > 0 && row > -1 && (
                  <div className='meeting-report-table' id="meeting-report-table">
                    <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@fw6vo8`} comsWeaTableStore={tableStore} getColumns={this.getColumns} scroll={{ y: 240 }}/>
                  </div>
                )
              }
            </div>
          </WeaTop>
        </WeaRightMenu>

        <MeetingDialog ecId={`${this && this.props && this.props.ecId || ''}_MeetingDialog@hw16it`}
          setRoomPlan={this.setRoomPlan}
          setDialog={this.setDialog}
          setType={this.setType}
          setMeetingId={this.setMeetingId}
          setAll={this.setAll}
          type={dialogType}//新建为'create',查看为'preview',编辑edit,会议决议---待定
          visible={visible}//显隐受控
          /* doClose={()=>{this.close()}}//关闭回调, 保存等按钮会自动调用该回调，可以在这里写一些页面的刷新操作 */
          /* onlyClose={() => { onlyClose() }}//关闭回调,关闭/取消等按钮会自动调用该回调，只做关闭操作 */
          doRefesh={this.doRefesh}//自定义刷新页面，不会关掉弹出框
          meetingId={meetingId} //会议id，查看会议时用到
          isInterval={true}//新建会议类型，true是周期会议， false是普通会议
          meetingDate={''}//新建日期
        />
        
        {RoomPlanContainer && <RoomPlanDialog ecId={`${this && this.props && this.props.ecId || ''}_RoomPlanDialog@j490xy`}
          setRoomPlan={this.setRoomPlan}
          setDialog={this.setDialog}
          setType={this.setType}
          setMeetingId={this.setMeetingId}
          canCreate={false}
          height={600}
          visible={RoomPlanContainer}/>}
<iframe name="exportExcel" src={exportExcelUrl} style={{display: 'none'}}></iframe>
      </div>
    )
  }

  doRefesh = ()=>{
    const { meetingMeetingReport } = this.props;
    let { getDetail, year, col, conditionParams,getReportCondition, type } = meetingMeetingReport;
    let params = 
    {
      year,
      month: col,
      orgType: conditionParams.orgType,
      yearType: conditionParams.yearType,
      type: type
    };
    if (conditionParams.orgType === '2') params = { ...params, subid: conditionParams.subid};
    if (conditionParams.orgType === '3') params = { ...params, depid: conditionParams.depid};
    getReportCondition();
    getDetail(params);
  }

  setAll = (meetingId, bool, type) => {
    this.setState({
      meetingId: meetingId,
      visible: bool,
      dialogType: type
    })
  }
  setMeetingId = (meetingId) => {
    this.setState({meetingId: meetingId})
  }
  setRoomPlan = (bool) => {
    this.setState({RoomPlanContainer: bool})
  }
  setDialog = (bool) => {
    this.setState({visible: bool})
  }
  setType = (type) => {
    this.setState({dialogType: type})
  }

  getColumns = (e) => {
    let newColumns = '';
    newColumns = e.map(column => {
      let newColumn = column;
      newColumn.render = (text, record, index) => { //前端元素转义
        let valueSpan = record[newColumn.dataIndex + "span"] !== undefined ? record[newColumn.dataIndex + "span"] : record[newColumn.dataIndex];
        return (
          newColumn.dataIndex == 'name' ?
            <div className="wea-url-name" style={{cursor: 'pointer'}} onClick={() => {
              this.setState({visible: true, dialogType: 'preview', meetingId: record.id})
            }} dangerouslySetInnerHTML={{__html:valueSpan}}/>
            :
            <div className="wea-url" dangerouslySetInnerHTML={{__html: valueSpan}}/>
  
        )
      }
      return newColumn;
    });
    return newColumns;
  }

}



//组件检错机制
class MyErrorHandler extends React.Component {
  render() {
    const hasErrorMsg = this.props.error && this.props.error !== "";
    return (
      <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@wer3we`} msg={hasErrorMsg ? this.props.error : getLabel(383324, "对不起，该页面异常，请联系管理员")} />
    );
  }
}

MeetingReport = WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(MeetingReport);

export default MeetingReport
